<?php

class Db_Tables_BjmProducts extends Zend_Db_Table
{
    protected $_name = 'bjm_products';
	var $member_id;
	var $num;
	var $taobao_id;
	
	function ProductExist($taobao_id)
	{
		$result = 0;
		
		if($taobao_id)
		{
			$row = $this->fetchRow("taobao_id='".trim($taobao_id)."'");
			
			if($row)
			{
				$result = 1;
			}
		}
		
		return $result;
	}
	
	function ProductsToBeSent()
	{
		$result = array();
		
		if($this->member_id)
		{
			$mod_link = new Db_Tables_BjmMembersLink();
			$mod_link->member_id = $this->member_id;
			$products_sent = $mod_link->ProductsSent();
			
			$select = $this->select();
			$select->from($this->_name, array("product_id", "product_url"));
			if(0 < count($products_sent))
			{
				$select->where("product_id NOT IN (?)", $products_sent);
			}
			$select->where("status = ?", 1);
			$select->where("coupon_expired_date >= ?", date("Y-m-d"));
			$select->order("product_id ASC");
			if(intval($this->num) && $this->num > 0)
			{
				$ct = $this->num;
			}else{
				$ct = 1000;
			}
			
			$select->limit($ct);
			$rows = $this->fetchAll($select);
			
			if($rows)
			{
				$mod_types = new Db_Tables_BjmMembersLinkType();
				$mod_types->member_id = $this->member_id;
				$types = $mod_types->GetTypesId();
				
				foreach($rows as $row)
				{
					$result[$row['product_id']] = urlencode($row['product_url']);
					
					//initial member's links
					foreach($types as $mtid)
					{
						$lrow = $mod_link->createRow();
						$lrow->mtid = $mtid;
						$lrow->product_id = $row['product_id'];
						$lrow->save();
					}
				}
			}
		}
		
		return $result;
	}
	
	function GetActiveProductsToRefresh()
	{
		$result = array();
		
		$select = $this->select();
		$select->from($this->_name, array("product_id", "product_url", "coupon_url"));
		$select->where("status = ?", 1);
		$select->order("last_refresh ASC");
		$rows = $this->fetchAll($select);
		
		if($rows)
		{
			foreach($rows as $row)
			{
				$result[$row["product_id"]] = array(
					'product_url' => $row["product_url"],
					'coupon_url' => $row["coupon_url"]
				);
			}
		}
		
		return $result;
	}
}